﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command.MenuaLL;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler.MenuaLL
{
    public class UpdateMenusCommandHandler : IRequestHandler<UpdateMenusCommand, ApiResult<int>>
    {
        IBaseReponsitory<Menus> Menus;

        public UpdateMenusCommandHandler(IBaseReponsitory<Menus> Menus)
        {
            this.Menus = Menus;
        }

        public async Task<ApiResult<int>> Handle(UpdateMenusCommand request, CancellationToken cancellationToken)
        {
            if (request.menus.Menu_Name == "")
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "菜单名称不为空",
                };
            }
            if (request.menus.Menu_Url == "")
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "跳转的URl地址不为空",
                };
            }

            var Tst = Menus.GetQuery().Where(x => x.Menu_Name == request.menus.Menu_Name && x.Menu_Id != request.menus.Menu_Id && !x.Menu_IsDel).ToList();
            if (Tst.Count > 0)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.False,
                    Message = "用户名称已存在",
                    Data = -1
                };
            }
            else
            {
                var list = await Menus.GetQuery().FirstOrDefaultAsync(c => c.Menu_Id == request.menus.Menu_Id);
                list.Menu_Name = request.menus.Menu_Name;
                list.Menu_Url = request.menus.Menu_Url;
                list.P_Id = request.menus.P_Id;
                list.Create_By = request.menus.Create_By;
                list.Update_By = request.menus.Update_By;
                list.Update_Date = DateTime.Now;
                await Menus.UpdateAsync(list);
                return new ApiResult<int>
                {
                    Code = ApiEnum.Success,
                    Message = "修改菜单成功",
                    Data = 1
                };
            }
        }
    }
}
